package com.saoft.jcms.web.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("fs")
public class FileSystemUploadController {

    @Value("${jcms.upload-path}")
    private String uploadBasePath;

    @ResponseBody
    @PostMapping("upload")
    public Map<String, Object> upload(MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        try {
            String originalFilename = file.getOriginalFilename();
            String type = FileTypeUtil.getType(originalFilename);
            if (type == null) {
                type = ".jpg";
            }
            String formatDate = DateUtil.formatDate(new Date());

            String fileName = IdUtil.fastUUID() + type;

            File file1 = new File(uploadBasePath + formatDate, fileName);

            /**/
            FileUtil.mkParentDirs(file1);

            file.transferTo(file1);

            String location = "/uploads/" + formatDate + "/" + fileName;
            map.put("location", location);

        } catch (IOException e) {
            e.printStackTrace();
            map.put("location", "");
        }
        return map;
    }

}
